package tree;

import java.util.Vector;

public class TreeNode {
    public TreeNode() {
        this.type = TREE_LEAF;
        this.parent = null;
        this.children = new Vector();
    }

    public void addChild(TreeNode child) {
        insertChild(child, this.children.size());
    }

    public void addChildAtIndex(TreeNode child, int index) {
        insertChild(child, index);
    }

    protected void insertChild(TreeNode child, int index) {
        if (child != null) {
            this.type = TREE_INODE;
            child.parent = this;
            this.children.add(index, child);
        }
    }

    public int removeChild(TreeNode child) {
        int index = -1;

        if (child != null) {
            index = this.children.indexOf(child);
            if (index >= 0) {
                this.children.remove(child);
                child.parent = null;
                if (this.children.size() == 0) {
                    this.type = TREE_LEAF;
                }
            } else {
                assert(false);
            }
        }

        return index;
    }

    public int getType() {
        int rval;

        if (this.children.size() == 0) {
            rval = TREE_LEAF;
        } else {
            rval = TREE_INODE;
        }
        assert (rval == this.type);
        return rval;
    }

    public int type;

    public TreeNode parent;
    public Vector children;

    public static int TREE_LEAF = 0;
    public static int TREE_INODE = 1;
}
